package com.leyou.cart.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.cart.entity.Cart;
import com.leyou.cart.interceptors.UserInfoInterceptor;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserInfoInterceptor userInfoInterceptor;

    private String KEY_PREFIX = "ly:cart:user:id:";

    public void addCart(Cart cart) {

        UserInfo userInfo = userInfoInterceptor.getUserInfo();
        Long id = userInfo.getId();
        String key = KEY_PREFIX + String.valueOf(id);

        //根据用户的id获取用户对应的购物车数据
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);

        String hKey = String.valueOf(cart.getSkuId());

        //判断这个用户的购物车是否加入过这个sku
        if(ops.hasKey(hKey)){    //这个sku已存在
            //要取出redis中存放的值，然后将其从json转为cart对象
            Cart storeCart = JsonUtils.nativeRead(ops.get(hKey), new TypeReference<Cart>() {
            });
            //修改数量，重新保存
            storeCart.setNum(storeCart.getNum()+cart.getNum());

            ops.put(hKey,JsonUtils.toString(storeCart));

        }else { //这个sku没有添加过，直接加入
            ops.put(hKey, JsonUtils.toString(cart));
        }
    }

    public List<Cart> queryCartList() {

        UserInfo userInfo = userInfoInterceptor.getUserInfo();
        Long id = userInfo.getId();
        String key = KEY_PREFIX + String.valueOf(id);

        //如果用户id对应的值为空，直接返回异常
        if (!redisTemplate.hasKey(key)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        //根据用户的id获取用户对应的购物车数据
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);

        //一次性取出所有的购物车数据
        List<String> cartListJson = ops.values();

        //循环把购物车数据从json转换为java对象
        List<Cart> cartList = cartListJson.stream()
                .map(ct -> JsonUtils.nativeRead(ct, new TypeReference<Cart>() {
                })).collect(Collectors.toList());

        return cartList;
    }

    public void modifyNum(String id, Integer num) {

        //获取当前用户
        Long userId = userInfoInterceptor.getUserInfo().getId();
        String key = KEY_PREFIX + userId;

        //判断该用户是否还有购物车数据
        if (!redisTemplate.hasKey(key)) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(key);

        String hKey = String.valueOf(id);
        //判断要修改的商品是否存在
        if (!ops.hasKey(hKey)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        } else{
            //数据库中储存的值
            Cart cart = JsonUtils.nativeRead(ops.get(hKey), new TypeReference<Cart>() {
            });
            //赋值给cart最新的值
            cart.setNum(num);

            ops.put(hKey,JsonUtils.toString(cart));
        }
    }


    public void addCartPatch(List<Cart> carts) {
        //对于每个购物车对象而言，都要判断是否在redis中加入，如果加入过就修改数量
        carts.forEach(cart -> addCart(cart));

    }
}
